/**
 * Created by Administrator on 2017/4/6 0006.
 */
var React = require('react');

var Bheader = require('../widget/Bheader');
var ajax = require('../tools/ajax');
var Icon = require('../components/Icon');
var MsgBox = require('../components/MsgBox');

module.exports = React.createClass({
    getInitialState: function () {
        return {
            addressInfo:"",//默认地址
            orderInfo:[],//订单商品信息
            numGoods:[],
            addressBox:"",//地址
            zhiBaoFlag:true,  //支付bao方式
            zhiWeiFlag:false,  //支付wei方式
            zhiFuM:"zhiFuBao", //需要那个方式结算
            order_comment:"",//留言
            is_point_order:0//是否为积分订单
        }
    },

    componentDidMount: function () {
        var p = this;
        setTimeout(function () {
            p.getAddressByUid();
            p.getOrderByUserId();
        }, 100);
        window.getOrderId = this.getOrderId;
        setTimeout(p.iscroll,500);
    },

    iscroll(){
        var p =this;
        p.myScroll = new IScroll("#orderInfoWrapper",{
            // 默认iscroll会拦截元素的默认事件处理函数，我们需要响应onClick，因此要配置
            preventDefault: false,
            // 禁止缩放
            zoom: false,
            // 支持鼠标事件，因为我开发是PC鼠标模拟的
            mouseWheel: true,
            // 滚动事件的探测灵敏度，1-3，越高越灵敏，兼容性越好，性能越差
            probeType: 3,
            // 拖拽超过上下界后出现弹射动画效果，用于实现下拉/上拉刷新
            bounce: true,
            // 展示滚动条
            scrollbars: false
        });
    },

    /**根据UserId获取默认收货地址*/
    getAddressByUid(){
        var p = this;
        var uid = localStorage.getItem("userId");
        var orderId = localStorage.getItem("orderId");
        ajax("POST","getAddressByUid",{uid:uid},function(dt){
            if(dt && dt.success){
                var objs = dt.data;
                if(objs[0]){
                    var addressBox = objs.map(function(obj){
                        if(obj.isdefault === 1) {
                            p.setState({addressInfo:obj},()=>{
                                ajax("POST","UpdateAddressToOrderInfo",{user_id:uid,orderId:orderId,addressInfo:JSON.stringify(obj)},function(dt){
                                    if(dt&&dt.success){
                                        console.log("增加地址成功");
                                    }
                                });
                            });
                            var idnumber = obj.idnumber.replace(obj.idnumber.substr(10,6), "******");
                            return (
                                <div key={obj.id} className="addressBox" onClick={p.changeAddress}>
                                    <span>{obj.realname}</span>
                                    <span>{obj.mobile}</span>
                                    <span>{obj.zipcode}</span>
                                    <p>{idnumber}</p>
                                    <p>{obj.province + obj.city + obj.district + obj.area + obj.address}</p >
                                    <Icon icon="#icon-fanhui"/>
                                </div>
                            )
                        }
                    });
                    p.setState({addressBox:addressBox});
                }else{
                    var obj = function(){
                        return(
                            <div className='addressBox noAddress' onClick={p.changeAddress}>
                                <p>请选择收货地址</p>
                                <Icon icon='#icon-fanhui'/>
                            </div>
                        )};
                    var addressBox = obj();
                    p.setState({addressBox:addressBox});
                }
            }
        });
    },
    changeAddress(){
        location.href = "#addressInfo";
        localStorage.setItem("orderFlag",1);
    },
    /**根据UserId获取商品订单信息*/
    getOrderByUserId(){
        var p = this;
        var userId = localStorage.getItem("userId");
        var orderId = localStorage.getItem("orderId");
        ajax("POST","getOrderByUserId",{userId:userId,orderId:orderId},function(dt){
            if(dt && dt.success){
                var objs = dt.data;
                console.log(objs);
                p.setState({is_point_order:objs[0].is_point_order,orderInfo:objs,order_comment:objs[0].order_comment},()=>{
                    var proList = objs.map(function (obj,index) {
                        if(obj.goods_img){
                            var goods_img = obj.goods_img.split(",")[0];
                        }
                        return (
                            <div key={index} className="proBuy" style={{borderTop:index?"1px solid #ccc":""}}>
                                <div className="proImg">
                                    <img src={goods_img} />
                                </div>
                                <div className="proRt">
                                    <div className="shopname">{obj.shopname?obj.shopname:"跨乐购平台"}</div>
                                    <p className="name">{obj.goods_name}</p>
                                    <div className="Number">{obj.goods_number}件</div>
                                    <div className="Price">{p.state.is_point_order?"¥"+obj.order_amount+"+"+obj.order_point+"积分":"¥"+obj.goods_price*obj.goods_number}</div>
                                </div>
                            </div>
                        )
                    });
                    p.setState({proList:proList});
                });
                if(objs[0].order_comment){
                    p.refs.liuyan.value = objs[0].order_comment;
                };
            }

        });

    },
    /**去支付 提供参数orderId*/
    PostOrder(){
        var p =this;
        var userId = localStorage.getItem("userId");
        var orderId = localStorage.getItem("orderId");
        var order_comment = this.refs.liuyan.value;
        console.log(order_comment);
        if(p.state.addressInfo){
            var addressInfo = JSON.stringify(p.state.addressInfo);
            ajax("POST","UpdateAddressToOrderInfo",{user_id:userId,orderId:orderId,addressInfo:addressInfo,order_comment:order_comment},function(dt){
                if(dt&&dt.success){
                    console.log("增加地址成功");
                }
            });
            if(p.state.zhiBaoFlag){
                console.log("支付宝");
                if(window.jsbridge){
                    window.jsbridge.getOrderId(orderId);
                }
                if(window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.interOp && window.webkit.messageHandlers.interOp.postMessage){
                    var message = {"method":"alipay","orderId":orderId};
                    window.webkit.messageHandlers.interOp.postMessage(message);
                }
            }else if(p.state.zhiWeiFlag){
                console.log("微信");
                if(window.jsbridge){
                    window.jsbridge.wxPay(orderId);
                }
                if(window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.interOp && window.webkit.messageHandlers.interOp.postMessage){
                    var message = {"method":"wxpay","orderId":orderId};
                    window.webkit.messageHandlers.interOp.postMessage(message);
                    /*
                    p.refs.MsgBox.setState({
                        type: "no",
                        timeout:2000,
                        show:true,
                        word:"微信支付开发中。。"
                    })
                    */
                }
            }
            window.payResultCallBack = function (flag) {
                localStorage.setItem("payStatus",flag);
                location.href = "#paySuccess";
            }
        }else{
            p.refs.MsgBox.setState({
                type: "no",
                timeout:3000,
                show:true,
                word:"请选择收货地址"
            })
        }
    },
    payMethodOne:function (e) {
        var p=this;
        var zhiFu = e.currentTarget.getAttribute("data-zhi");
        if(zhiFu=="zhiFuBao"){
            p.setState({zhiBaoFlag:true});
            p.setState({zhiWeiFlag:false})
        }else if(zhiFu=="zhiFuWei"){
            p.setState({zhiBaoFlag:false});
            p.setState({zhiWeiFlag:true})
        }
    },

    render: function () {
        var p = this;
        var orderInfo = this.state.orderInfo;
        if(orderInfo.length>0){
            localStorage.setItem("AllPrice",orderInfo[0].order_amount);
            return (
                <div className="main"  id="main">
                    <Bheader title="确认订单" headr="false" hact="#"></Bheader>
                    <div className="container-t wrap" id="orderInfoWrapper">
                       <div className="orderInfoPay">
                           {p.state.addressBox}
                           <div className="proBuybox">
                               {p.state.proList}
                           </div>
                           <div className="liuyan">
                               <p>订单留言</p >
                               <input type="text" ref="liuyan" placeholder="选填：对本次交易的说明" />
                           </div>
                           <div id="payM">
                               <div className="paymentMethod">
                                   <p className="paymentMethodText"  style={{fontSize:"0.7rem",color: "#000000",lineHeight:"1.2rem"}}>支付方式</p>
                                   <div className="paymentMethodBao">
                                       <Icon icon="#icon-zhifubaozhifu" style={{fontSize:"1.05rem"}}/>
                                       <span>支付宝支付</span>
                                       <label className={p.state.zhiBaoFlag?"fr checked":"fr"} onClick={p.payMethodOne} data-zhi="zhiFuBao"><Icon icon="#icon-xuanzhong1" style={{fontSize:"1rem"}}/></label>
                                   </div>
                                   <div className="paymentMethodWei">
                                       <Icon icon="#icon-weixinzhifu" style={{fontSize:"1.05rem"}}/>
                                       <span>微信支付</span>
                                       <label className={p.state.zhiWeiFlag?"fr checked":"fr"} onClick={p.payMethodOne}  data-zhi="zhiFuWei"><Icon icon="#icon-xuanzhong1" style={{fontSize:"1rem",}}/></label>
                                   </div>
                               </div>
                           </div>
                           <div className="feiyong" style={{display:p.state.is_point_order?"none":"block"}} >
                               <div className="priceLine">
                                   商品总金额
                                   <span className="priceStyle">¥{orderInfo[0].goods_amount}</span>
                               </div>
                               <div className="priceLine">
                                   运费
                                   <span className="priceStyle">¥{orderInfo[0].shipping_fee}</span>
                               </div>
                               <div className="priceLine">
                                   关税
                                   <span className="priceStyle">¥{orderInfo[0].goods_tax}</span>
                               </div>
                               <div style={{height:"0.6rem"}}>
                                   <span className="priceStyle"></span>
                               </div>
                           </div>
                       </div>
                    </div>
                    <div className="tjDingdan">
                        <p>
                            <label className="num">共{orderInfo.length}件商品&nbsp;&nbsp;&nbsp;</label>
                            <label className="price">合计:{p.state.is_point_order?orderInfo[0].order_amount+"元":orderInfo[0].order_amount+"元"}</label>
                        </p>
                        <p className="tjBtn" onClick={p.PostOrder}>去支付</p>
                    </div>
                    <MsgBox ref="MsgBox"></MsgBox>
                </div>
            )
        }else{
            return(
                <div>
                    <MsgBox ref="MsgBox"></MsgBox>
                </div>
            )
        }
    }
});

